package com.googlecode.garbagecan.jmsstudy.openjms;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueReceiveAsynchronous implements MessageListener {
	private QueueConnection queueConnection;
	private QueueSession queueSession;
	private Queue queue;
	private QueueReceiver queueReceiver;

	public static void main(String[] args) {
		new QueueReceiveAsynchronous();
	}
	
	public QueueReceiveAsynchronous() {
		try {
			Hashtable properties = new Hashtable();
			properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory");
			properties.put(Context.PROVIDER_URL, "rmi://localhost:1099/");
			Context context = new InitialContext(properties);

			QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("JmsQueueConnectionFactory");
			queueConnection = queueConnectionFactory.createQueueConnection();
			queueConnection.start();
			
			queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			queue = (Queue) context.lookup("queue1");

			queueReceiver = queueSession.createReceiver(queue);
			queueReceiver.setMessageListener(this);
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				String messageText = ((TextMessage) message).getText();
				System.out.println(messageText);
			}
		} catch (JMSException ex) {
			ex.printStackTrace();
		}
	}
}
